<template>
  <div class="tracks-add-page">
    <u-navbar
      :title="isAdd ? '添加逐鹿' : '编辑逐鹿'"
      :title-style="{ 'font-weight': 'bold', 'font-size': '18px' }"
      fixed
      placeholder
      @leftClick="handleBack"
    ></u-navbar>
    <div class="tracks-add-content">
      <div class="gac-item"  @click="focusInput(['detail', 'trackname'])">
        <span class="gac-required">*</span>
        <u--input
          clearable
          v-model="detail.trackname"
         
          class="shop-add-input"
          placeholder="请输入名称"
          border="none"
          color="black"
        ></u--input>
      </div>

      <div
        class="gac-item"
        @click="showPicker = true"
      >
        <span class="gac-required required-status">*</span>
        <text
          v-if="pickvalue"
          class="search-selected-status"
        >
          {{ pickvalue }}
        </text>
        <text
          v-else
          class="search-status"
        >
          请选择等级
        </text>
        <u-picker
          :show="showPicker"
          :columns="columns"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        ></u-picker>
        <u-icon
          color="#bfbfbf"
          name="arrow-right"
        ></u-icon>
      </div>

      <div class="gac-item gac-mark-item"  @click="focusInput(['detail', 'mark'])">
        <u--textarea
          v-model="detail.mark"
          placeholder="请输入备注"
         
          border="none"
          count
          :max-length="50"
          ></u--textarea>
      </div>


    

      <div class="track-cell" v-for="(itemDetail, index) in lists" :key="itemDetail.id">
        <div class="first-row">
              <u--input
                clearable
                v-model="lists[index].title"
                class="first-input"
                placeholder="请输入记录标题"
                @focus="focusInput(['lists', index, 'title'])"
                border="none"
                color="black"
              ></u--input>

             <div class="first-right">
                      <div class="first-time">
                        <span
                          v-if="itemDetail.time"
                          class="first-date"
                          @click="showDatePoup(index)"
                        >
                          {{ getDay(itemDetail.time) }}
                        </span>
                        <span
                          v-else
                          class="first-date first-t-empty"
                          @click="showDatePoup(index)"
                        >
                          选择日期
                        </span>
                        <u-icon
                          color="#bfbfbf"
                          name="arrow-right"
                        ></u-icon>
                    </div>
                    <div class="first-btns">
                      <span v-if="index!==0" @click="upCellClick(index)" class="first-up-btn">上移</span>
                      <span @click="delCellClick(index)" class="first-del-btn">删除</span>
                    </div>
                    
             </div>
        </div>

    
      <div class="gac-item gac-mark-item"  @click="focusInput(['lists', index, 'des'])">
        <u--textarea
          v-model="lists[index].des"
          placeholder="请输入备注"
         
          border="none"
          count
          :max-length="50"
          ></u--textarea>
      </div>

      <div class="gac-item gac-img-item">
        <ImageUploader
            :flagtip="imgtiper(itemDetail.title)"
            :value="itemDetail.imgUrls"
            @change="handleUpload($event, index)"
          />
      </div>

      </div>

      <div class="add-cell-btn" @click="addlist"> + 新增一条 记录</div>

      <u-modal
      :show="showcelldel"
      :show-cancel-button="true"
      content="确认要删除记录吗？"
      @confirm="delCellConfirm"
      @cancel="showcelldel = false"
    ></u-modal>
      <u-modal
      :show="showcellUp"
      :show-cancel-button="true"
      content="确认要上移吗？"
      @confirm="upCellConfirm"
      @cancel="showcellUp = false"
    ></u-modal>

    <u-datetime-picker
              v-model="lists[activeCellIndex].time"
              :show="showdate"
              mode="datetime"
              @confirm="dateConfirm"
              @cancel="dateCancel"
            ></u-datetime-picker>
   
    </div>
    <u-modal
      :show="showdel"
      :show-cancel-button="true"
      content="确认要删除吗？"
      @confirm="delConfirm"
      @cancel="showdel = false"
    ></u-modal>
    <Speecher @handler="handlerSpeecher" />
    <div class="gac-footer">
      <span 
      v-if="!isAdd" 
      class="gac-submit-del" 
      @click="deleteClick"
      >
      删除
    </span>
      <span 
      class="gac-submit-ok" 
      @click="submitok"
      >
      提交
    </span>
    </div>
  

  </div>
</template>

<script>
import dayjs from 'dayjs'
import ImageUploader from '../../components/imageUploader/image-uploader.vue'
import Speecher from '../../components/speecher/speecher.vue'

let number = 1;

const statusTxts = {
  1: '开始',
  2: '20%',
  3: '50%',
  4: '80%',
  5: '完成',
};

export default {
  name: 'CookAdd',
  layout: 'barHeight',
  components: {
    ImageUploader,
    Speecher,
  },
  data() {
    return {
      detail: {
        mark: '',
      },
      showdate: false,
      pickerTime: '',
      activeCellIndex: 0,
      showdel: false,
      showcelldel: false,
      showcellUp: false,
      date: '',
      addImgKey: 0,
      isAdd: true,
      activeInputLevels: [],
      maps: statusTxts,
      reverseMaps: Object.entries(statusTxts).reduce((acc, item) => {
        acc[item[1]] = item[0]
        return acc
      }, {}),
      pickvalue: statusTxts[1],
      showPicker: false,
      columns: [[...Object.values(statusTxts)]],
      lists: [
      {
                    "id": 1,
                    "title": "",
                     // "2024-04-10 20:06:36"
                    "time": dayjs().format('YYYY-MM-DD HH:mm'),
                    "imgUrls": [],
                    "des": ""
                }
      ],
    }
  },
  onLoad(options) {
    this.options = options || {}
    this.isMountedPageLoaded = true
    this.isAdd = !options.trackname
  },
  mounted() {
    if (!this.isAdd) {
      this.getdata()
    }
  },
  watch:{
    pickerTime(val){
      this.lists[this.activeCellIndex].time = val
    }

  },

  methods: {
  onclickSpeech() {
      this.speechClickTime = new Date().getTime()
    },
    focusInput(levels) {
      setTimeout(() => {
        const timer =  new Date().getTime()
        const intervalTime = Math.abs(timer - this.speechClickTime)
        // 透穿的行为应该是同时出现，所以，用300毫秒差不多
        if(intervalTime < 300){//间隔时间太少，说明是点击语音按钮时，透穿点击到了input，此时透穿应该无效
          return
        }
        this.activeInputLevels = levels
      }, 200);// 透穿的行为应该是同时出现，所以，用200毫秒等待差不多
    },
    handlerSpeecher(val) {
      const levels = this.activeInputLevels
      if(!levels?.length) return
      if(levels.length === 1){
        this[levels[0]] = val
      }
      if(levels.length === 2){
        this[levels[0]][levels[1]] = val
      }
      if(levels.length === 3){
        this[levels[0]][levels[1]][levels[2]] = val
      }
      if(levels.length === 4){
        this[levels[0]][levels[1]][levels[2]][levels[3]] = val
      }

      if(Array.isArray(this[levels[0]])){
        this[levels[0]] = [...this[levels[0]]]
      }else if(typeof this[levels[0]] === 'object'){
        this[levels[0]] = {...this[levels[0]]}
      }
      // 清除
      this.activeInputLevels = []
      
    },
    addlist() {
      return this.lists = [...this.lists,  {
                    "id": number++,
                    "title": "",
                    "time": dayjs().format('YYYY-MM-DD HH:mm'),
                    "imgUrls": [],
                    "des": ""
                }]
    },
    getDay(val) {
      return dayjs(val).format('YYYY-MM-DD HH:mm')
    },
    showDatePoup(index) {
      this.activeCellIndex = index
      console.log(index)
      this.showdate = true
    },
    handleBack() {
      uni.navigateBack({
        delta: 1,
      })
    },
     // 图片上传
    handleUpload(val, index) {
      this.lists[index].imgUrls = val
    },
    async submitAdd() {
      const params = {
        ...this.detail,
        status: Number(this.reverseMaps[this.pickvalue]),
        lists: this.lists,
      }
      console.log(params)
      const res = await this.$request.post('/track/add', params);
      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          duration: 1000,
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          })
        }, 1500)
      }
    },
    async submitedit() {
      const params = {
        ...this.detail,
        trackname: this.options.trackname,
        status: Number(this.reverseMaps[this.pickvalue]),
        lists: this.lists,
        newtrackname: this.detail.trackname,
      };
      const res = await this.$request.post('/track/update', params);
      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          duration: 1000,
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          })
        }, 1500)
      }
    },
    async delConfirm() {
      try {
        const params = {
              trackname: this.options.trackname,
            };
        const res = await this.$request.post('/track/del', params)
        if (res.code === 200) {
          uni.showToast({
            title: '删除成功',
            duration: 1000,
            icon: 'success',
            mask: true,
          })
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            })
          }, 1500)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async delCellConfirm() {
      const originLists = [...this.lists]
      originLists.splice(this.activeCellIndex, 1)
      this.lists = originLists
      this.showcelldel = false
    },
    async delCellClick(index) {
      this.activeCellIndex = index;
      this.showcelldel = true
    },
    async upCellClick(index) {
      this.activeCellIndex = index;
      this.showcellUp = true
    },
    async upCellConfirm() {
      const originLists = [...this.lists]
      const activeCell = originLists[this.activeCellIndex]
      originLists.splice(this.activeCellIndex, 1)
      originLists.splice(this.activeCellIndex-1, 0, activeCell )
      this.lists = originLists
      this.showcellUp = false
    },
    async deleteClick() {
      console.log('adsfas')
      this.showdel = true
    },
    submitok() {
      if (this.isAdd) {
        this.submitAdd()
      } else {
        this.submitedit()
      }
    },
   
    dateCancel() {
      this.showdate = false
    },
    dateConfirm(va) {
      console.log(va)
      this.showdate = false
    },
    onConfirm(args) {
      this.pickvalue = args.value[0]
      this.showPicker = false
    },
    imgtiper(title) {
      return `track_${this.detail.trackname}_${title}`
    },
    async getdata() {
      if (!this.options.trackname) return
      const response = await this.$request.post('/track/list', {
        pageNo: 1,
        pageSize: 200,
        trackname: this.options.trackname,
      });
      const res = response && response.data
      const detail = (res && res[0]) || {}
      this.pickvalue = this.maps[detail.status]
      this.lists = detail.lists
      this.detail = detail
    },
    back() {},

  },
};
</script>

<style lang="less">
.tracks-add-page {
  .gac-item {
    .u-textarea {
      background-color: transparent;
    }
    .u-textarea__count {
      background-color: transparent !important;
    }
    .u-textarea__field {
      color: black;
    }
  }
}
</style>

<style lang="less" scoped>
@height-wrap: 44px;
@paddingbottom: 8px;
.tracks-add-page {
      padding-bottom: 80px;
  .gac-required {
    color: red;
    font-size: 12px;
    margin-right: 7px;
  }
  .gac-item {
    display: flex;
    align-items: center;
    padding: 0 12px;
    margin: 0 16px;
    background: #f7f8fa;
    border-radius: 8px;
    height: 44px;
    margin-top: 12px;
  }
  .gac-mark-item {
    height: auto;
  }
  .gac-empty {
    color: #c8c9cc;
  }

  .gac-date {
    flex: 1;
  }
  .gac-input {
    background: transparent;
    padding-left: 0;
  }
  .gac-status {
    background: transparent;
  }
  .right-icon {
    color: #bfbfbf;
  }
  .gac-submit-del,
  .gac-submit-ok {
    height: 100%;
    line-height: 44px;
    font-size: 16px;
    border-radius: 22px;
    padding-left: 28px;
    padding-right: 28px;
  }
  .gac-footer {
    display: flex;
    position: fixed;
    bottom: 0;
    //让图层更高
    z-index: 2;
    left: 0;
    right: 0;
    justify-content: center;
    align-items: center;
    height: 60px;
    background: #fff;
    box-shadow: 0 -2px 2px rgba(0, 0, 0, 0.05);
    padding: @paddingbottom 16px;
  }
 
  .gac-submit-del {
    background: #f7f8fa;
    color: #131212;
    margin-right: 12px;
    text-align: center;
  }
  .gac-submit-ok {
    flex: 1;
    background: #538fff;
    text-align: center;
    color: #fff;
  }
  .gac-del-diable {
    background: #f7f8fa;
    color: #979797;
  }

  .gac-ok-diable {
    background: #d8d8d8;
    color: #fff;
  }

  .gac-img-item{
    height: auto;
    overflow-x: auto;
    background: transparent;
    padding: 0;
  }

  .search-selected-status{
    font-size: 15px;
  }

  .track-cell{

    .first-row{
      display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    border-top: 1px dashed #ffc69f;
    margin-top: 12px;
    padding-top: 12px;
    }
    .first-right{
          margin-left: 10px;
    width: 190px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    }
    .first-time{
      display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f7f8fa;
    height: 32px;
    margin: 0 5px;
    padding-left: 9px;
    padding-right: 3px;
    border-radius: 4px;
    }
    .first-btns{
          font-size: 12px;
    }
    .first-up-btn{
          color: #538fff;
    margin-right: 5px;
    }
    .first-del-btn{
          color: #ff755d;
    }
    .gac-mark-item{
      padding-left: 10px;
    }
    
  }

  .add-cell-btn{
        height: 32px;
    width: 150px;
    color: #538fff;
    display: flex;
    align-items: center;
    padding: 0 16px;
    font-size: 15px;
    margin-top: 14px;
  }
}
</style>

<style  lang="less">
.tracks-add-page {
    .track-cell{

    .u-input{
    background: #f7f8fa;
    height: 32px;
   padding-left: 10px!important;
   border-radius: 6px;
    }

    .u-textarea{
      padding-left: 0!important;
    }


    
  }

}


</style>
